package org.cb.input;

import java.awt.event.KeyEvent;
import java.util.Random;

import org.cb.client.Client;
import org.cb.core.ColourBot;
import org.cb.core.Global;

/**
 * 
 * @author Unknown
 * 
 * Edited to work with the new layout.
 * 
 * Not tested.
 *
 */
public class Keyboard {
	char[] spChars = {'~', '!', '@', '#', '%', '^', '&', '*', '(', ')', '_', '+', '{', '}', ':', '<', '>', '?', '"', '|'};
    char[] replace = {'`', '1', '2', '3', '5', '6', '7', '8', '9', '0', '-', '=', '[', ']', ';', ',', '.', '/', '\'', '\\'};
    Client client;
    
    
    private int getRandom() throws InterruptedException{
        Random rand = new Random();
        //lag var 47-219, usu 78-94; currently tends low
        return rand.nextInt(100) + 40;
    }
    
	public void sendKeys(String s, boolean pressEnter) throws InterruptedException{
        for (char c : s.toCharArray()) {
        	sendChar(c);
        	ColourBot.sleep(getRandom() * 2);
        }
        if(pressEnter)
        	sendChar((char) KeyEvent.VK_ENTER);
    }
	
	public void sendEnter() throws InterruptedException{
		sendChar((char) KeyEvent.VK_ENTER);
	}
	
	public void sendChar(char c) throws InterruptedException{
		long pressTime = System.currentTimeMillis();
		boolean isSpecial = false;
    	char check = specialCharacterCheck(c);
    	if(check != c) {
    		isSpecial = true;
    		c = check;
    	}
    	int keyCode = (int) c;
    	if(isSpecial || !Character.isLowerCase(c)) {
    		pressTime += getRandom();
    		
            Global.getTheCanvas().dispatchEvent(new KeyEvent(Global.getTheCanvas(), KeyEvent.KEY_PRESSED, pressTime, KeyEvent.SHIFT_MASK, keyCode, c));
            Global.getTheCanvas().dispatchEvent(new KeyEvent(Global.getTheCanvas(), KeyEvent.KEY_TYPED, pressTime, KeyEvent.SHIFT_MASK, 0, c));
            pressTime += getRandom();
            Global.getTheCanvas().dispatchEvent(new KeyEvent(Global.getTheCanvas(), KeyEvent.KEY_RELEASED, pressTime, KeyEvent.SHIFT_MASK, keyCode, c));
            pressTime += getRandom();
            Global.getTheCanvas().dispatchEvent(new KeyEvent(Global.getTheCanvas(), KeyEvent.KEY_RELEASED, pressTime, 0, KeyEvent.VK_SHIFT, KeyEvent.CHAR_UNDEFINED));
    	} else {
    		pressTime += getRandom();
    		Global.getTheCanvas().dispatchEvent(new KeyEvent(Global.getTheCanvas(), KeyEvent.KEY_PRESSED, pressTime, 0, keyCode, c));
    		Global.getTheCanvas().dispatchEvent(new KeyEvent(Global.getTheCanvas(), KeyEvent.KEY_TYPED, pressTime, 0, 0, c));
            pressTime += getRandom();
            Global.getTheCanvas().dispatchEvent(new KeyEvent(Global.getTheCanvas(), KeyEvent.KEY_RELEASED, pressTime, 0, keyCode, c));
    	}
	}
	
	public char specialCharacterCheck(char c) throws InterruptedException{
		int i = 0;
		for(char sp : spChars) {
			if(c == sp)
				return replace[i];
			i++;
		}
		return c;
	}
}
